<?php

namespace app\admin\controller;
use app\common\controller\AdminBase;
use app\common\model\Excel;
use app\common\model\OrderChange;
use app\common\model\OrderRefund;
use app\common\model\OrderVerify;
use app\common\model\Region;
use app\common\model\Settings;
use app\common\model\Merch;
use app\common\model\Order as M;
use think\App;
use think\Exception;
use think\facade\Request;
use think\facade\Db;
use think\facade\View;

class Order extends AdminBase
{
    private function getWhere($status){
        $where = get_order_where($status);

        //条件
        $key = input('key');
        if ($key!='') {
            $where[] = ['id', '=',  intval($key)];
        }

        $order_sn = input('order_sn');
        if ($order_sn!='') {
            $where[] = ['order_sn', 'like',  '%'.trim($order_sn).'%'];
        }

        $type=input('type');
        if (!empty($type)) {
            $where[] = ['type', '=',  intval($type)];
        }

        $activity_type=input('activity_type');
        if (!empty($activity_type)) {
            $where[] = ['activity_type', '=',  intval($activity_type)];
        }

        $goods = input('goods');
        if ($goods!='') {
            $id_arr = Db::name('order_goods')
                ->where('goods_id','=',intval($goods))
                ->whereOr('title','like','%'.trim($goods).'%')
                ->column('order_id');
            $where[] = ['id','in',$id_arr];
        }

        $verify_code = input('verify_code');
        if ($verify_code!='') {
            $where[] = ['verify_code','=',$verify_code];
        }

        $user=input('user');
        if (!empty($user)) {
            $uid = Db::name('users')
                ->where('id|mobile','=',trim($user))
                ->value('id');
            if($uid){
                $where[] = ['uid', '=',  intval($uid)];
            }else{
                $where[] = ['uid', '=',  -1];
            }
        }

        $merch=input('merch');
        if (!empty($merch)) {
            $where[] = ['merch_id', '=',  intval($merch)];
        }

        $pro_id = input('pro_id');
        if(!empty($pro_id)){
            $where[]=['pro_id','=',intval($pro_id)];
        }

        $city_id = input('city_id');
        if(!empty($city_id)){
            $where[]=['city_id','=',intval($city_id)];
        }

        $area_id = input('area_id');
        if(!empty($area_id)){
            $where[]=['area_id','=',intval($area_id)];
        }

        $is_change = input('is_change');
        if($is_change!=''){
            $where[]=['is_change','=',intval($is_change)];
        }

        $pay_type=input('pay_type');
        if (!empty($pay_type)) {
            $where[] = ['pay_type', '=',  intval($pay_type)];
        }

        //时间
        $time_type = input('time_type');
        if (!empty($time_type)) {
            //条件 开始时间
            $start_time = input('start_time');
            if (!empty($start_time)) {
                $where[] = [$time_type, '>=', strtotime($start_time)];
            }

            //条件 结束时间
            $end_time = input('end_time');
            if (!empty($end_time)) {
                $where[] = [$time_type, '<=', strtotime($end_time)];
            }
        }

        return $where;
    }

    //全部列表
    public function index($status='100'){

        if(Request::isAjax()) {

            //分页
            $page =input('page')?input('page'):1;
            $pageSize =input('limit')?input('limit'):config('pageSize');
            $page = ['list_rows'=> $pageSize, 'page' => $page];

            //查询条件
            $where = $this->getWhere($status);

            //排序
            $sort_order = input('sort_order') ? input('sort_order') : 'desc';
            $order = input('sort_order')?[input('sort_by')=>$sort_order]:['id'=>$sort_order];

            $list = Db::name('order')
                ->where($where)
                ->order($order)
                ->paginate($page)
                ->each(function ($item){
                    $item['type_html'] = get_base_type(2,$item['type']);
                    $item['activity_type_html'] = get_goods_activity_type(2,$item['activity_type']);

                    $item['status_str'] = get_order_status($item);

                    $item['transaction_id'] = show_transaction_id($item['pay_type'],$item['transaction_id']);

                    $item['pay_type_html'] = get_pay_type(2,$item['pay_type']);

      /*              $user = \app\common\model\Users::cacheNick($item['uid']);
                    $item['user_mobile'] = $user['mobile'];
                    $item['nickname'] = $user['nickname'];*/

                    $item['merch_title'] = \app\common\model\Merch::getTitle($item['merch_id']);

                    $order_goods = Db::name('order_goods')
                        ->where('order_id','=',$item['id'])
                        ->field('goods_id,title,short_title,thumb,sku,spec_item_title,price,num')
                        ->select()
                        ->toArray();

                    $item['order_goods'] = $order_goods;

                    $item['pro'] = Region::getRegionName($item['pro_id']);
                    $item['city'] = Region::getRegionName($item['city_id']);
                    $item['area'] = Region::getRegionName($item['area_id']);

                    $item['create_time'] = toDate($item['create_time']);
                    $item['pay_time'] = toDate($item['pay_time']);
                    $item['send_time'] = toDate($item['send_time']);
                    $item['receive_time']= toDate($item['receive_time']);
                    $item['cancel_time'] = toDate($item['cancel_time']);
                    $item['refund_apply_time'] = toDate($item['refund_apply_time']);
                    $item['refund_time']= toDate($item['refund_time']);
                    $item['change_apply_time'] = toDate($item['change_apply_time']);
                    $item['change_time']= toDate($item['change_time']);
                    return $item;
                })
                ->toArray();


            return ['code'=>0,'msg'=>'获取成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1];
        }else{

            $province = get_region(1);
            $view = [
                'status'=>$status,

                'pay_type'=>get_pay_type(),
                'type_list'=>get_base_type(),
                'goods_activity_type'=>get_goods_activity_type(),
                'province'=>$province,
                'merch_list' => \app\common\model\Merch::getList()
            ];
            return view('index',$view);
        }
    }

    //待付款
    public function pay(){
        return $this->index(0);
    }

    //待发货
    public function send(){
        return $this->index(1);
    }

    //待核销
    public function verify(){
        return $this->index(2);
    }

    //待收货
    public function receive(){
        return $this->index(3);
    }

    //已完成
    public function finish(){
        return $this->index(4);
    }

    //已取消
    public function cancel(){
        return $this->index(5);
    }

    //申请退款
    public function apply(){
        return $this->index(6);
    }

    //已退款
    public function refund(){
        return $this->index(7);
    }

    //申请换货
    public function change(){
        return $this->index(8);
    }

    //导出
    public function export(){
        ini_set("memory_limit", "512M");
        //查询条件
        $status = input('status');
        $where = $this->getWhere($status);

        //排序
        $sort_order = input('sort_order') ? input('sort_order') : 'desc';
        $order = input('sort_order')?[input('sort_by')=>$sort_order]:['id'=>$sort_order];

        $list = Db::name('order')
            ->where($where)
            ->order($order)
            ->select()
            ->toArray();

        $arr = [];
        foreach ($list as $item){


            $item['type_str'] = get_base_type(3,$item['type']);
            $item['activity_type_name'] = get_goods_activity_type(3,$item['activity_type']);
            $item['verify_type_str']='';
            if($item['type']==1) {
                $item['verify_type_str'] = get_goods_verify_type(3, $item['verify_type']);
            }

            $item['status_str'] = get_order_status($item);

            $user = \app\common\model\Users::cacheNick($item['uid']);
            $item['user_mobile'] = $user['mobile'];
            $item['nickname'] = $user['nickname'];

            $item['merch_title'] = \app\common\model\Merch::getTitle($item['merch_id']);

            $item['pro'] = Region::getRegionName($item['pro_id']);
            $item['city'] = Region::getRegionName($item['city_id']);
            $item['area'] = Region::getRegionName($item['area_id']);
            $item['send_address'] = $this->showAddress($item);

            $item['pay_type_title'] = get_pay_type(3,$item['pay_type']);

            $item['create_time'] = toDate($item['create_time']);
            $item['pay_time'] = toDate($item['pay_time']);
            $item['send_time'] = toDate($item['send_time']);
            $item['receive_time']= toDate($item['receive_time']);

            $order_goods = Db::name('order_goods')
                ->where('order_id','=',$item['id'])
                ->field('goods_id,title,short_title,thumb,sku,spec_item_title,price,num,leave_num')
                ->select()
                ->toArray();

            foreach ($order_goods as $key=>$go){
                if($item['type']==1&&$item['verify_type']==2){
                    $leave_num = $go['leave_num'];
                }else{
                    $leave_num = '';
                }

                $temp = [
                    'id'=>$item['id'],
                    'order_sn'=>$item['order_sn'],
                    'status_str'=>$item['status_str'],
                    'type'=>$item['type_str'],
                    'activity_type_name'=>$item['activity_type_name'],
                    'verify_type'=>$item['verify_type_str'],
                    'verify_code'=>$item['verify_code'],

                    'goods_id'=>$go['goods_id'],
                    'title'=>$go['title'],
                    'sku'=>$go['sku'],
                    'spec_item_title'=>$go['spec_item_title'],
                    'price'=>$go['price'],
                    'num'=>$go['num'],
                    'leave_num'=>$leave_num,

                    'order_price'=>$key==0 ? $item['order_price'] : 0,
                    'goods_price'=>$key==0 ? $item['goods_price'] : 0,
                    'dispatch_price'=>$key==0 ? $item['dispatch_price'] : 0,
                    //Totag 隐藏积分抵扣
//                    'coin'=>$key==0 ? $item['coin'] : 0,
//                    'coin_deduct'=>$key==0 ? $item['coin_deduct'] : 0,
                    'merch_price'=>$key==0 ? $item['merch_price'] : 0,

                    'pay_type_title'=>$item['pay_type_title'],
                    'transaction_id'=>show_transaction_id($item['pay_type'],$item['transaction_id']),
                    'pay_price'=>$item['pay_price'],
                    'pay_time'=>$item['pay_time'],

                    'uid'=>$item['uid'],
                    'nickname'=>$item['nickname'],
                    'mobile'=>$item['user_mobile']."\t",

                    'merch_id'=>$item['merch_id'],
                    'merch_title'=>$item['merch_title'],

                    'pro'=>$item['pro'],
                    'city'=>$item['city'],
                    'area'=>$item['area'],
                    'create_time'=>$item['create_time'],
                    'note'=>$item['note'],

                    'send_name'=>$item['send_name'],
                    'send_mobile'=>$item['send_mobile']."\t",
                    'send_address'=>$item['send_address'],
                    'send_express'=>$item['send_express'],
                    'send_sn'=>$item['send_sn'],
                    'send_time'=>$item['send_time'],
                    'receive_time'=>$item['receive_time'],
                ];

                $arr[] = $temp;
            }
        }

        $header = [
            '编号','订单单号','状态','订单类型','活动类型','核销类型','核销码',
            '商品编号','商品名称','规格标识','规格名称','商品单价','购买数量','核销剩余数量',
            '订单总价','商品总价','运费',
            //Totag 隐藏积分抵扣
//            "使用".config('self.user_coin_title')."数量",
//            config('self.user_coin_title')."抵扣金额",
            '商家结算金额',
            '支付方式','支付单号','支付金额','支付时间',
            '会员编号','会员昵称','会员手机',
            '商家编号','商家名称',
            '省份','城市','县区','下单时间','备注',
            '收货人','收货手机号','收货地址','快递公司','快递单号','发货时间','收货时间'
        ];
        Excel::export('订单记录',$header,$arr);
    }

    //删除
    public function del($id){
        try{
            M::orderDel($id);
            return $this->returnSuccess('删除成功');
        }catch (\Exception $exception){
            global $admin_has_exception;
            $admin_has_exception = true;
            return $this->returnError($exception->getMessage());
        }
    }

    //详情
    public function detail(){
        $id = input('id');

        $order = Db::name('order')
            ->where('id','=',$id)
            ->find();

        if(!$order){
            die('无此订单信息');
        }

        $order_goods = Db::name('order_goods')
            ->where('order_id','=',$id)
            ->select()
            ->toArray();

        $user = \app\common\model\Users::cacheNick($order['uid']);

        $merch = \app\common\model\Merch::getInfo($order['merch_id']);

        $order['send_address'] = $this->showAddress($order);

        //退款信息
        $order_refund = OrderRefund::where('order_id',$order['id'])->find();
        $order_refund['imgs'] = empty($order_refund['imgs']) ? [] : json_decode($order_refund['imgs'],true);

        //换货信息
        $order_change = OrderChange::where('order_id',$order['id'])->find();
        $order_change['imgs'] = empty($order_change['imgs']) ? [] : json_decode($order_change['imgs'],true);

        $view = [
            'order'=>$order,
            'order_goods'=>$order_goods,
            'order_refund'=>$order_refund,
            'order_change'=>$order_change,
            'user'=>$user,
            'merch'=>$merch,
        ];
        return view('',$view);
    }

    public function showAddress($order){
        $pro = Region::getRegionName($order['pro_id']);
        $city = Region::getRegionName($order['city_id']);
        $area = Region::getRegionName($order['area_id']);
        $address = $pro.' '.$city.' '.$area.' '.$order['send_address'];
        return $address;
    }

    //发货修改发货
    public function doSend(){
        $id = input('id');
        if(request()->isGet()){
            $order = M::where('id','=',$id)
                ->field('id,order_sn,type,activity_type,status,send_name,send_mobile,pro_id,city_id,area_id,send_address,send_express_id,send_time,send_sn')
                ->find();
            $order['send_address'] = $this->showAddress($order);
            $order['send_time'] = toDate($order['send_time']);
            $view = [
                'express'=>Settings::getSettings(ZFN_SETTINGS_EXPRESS),
                'info'=>$order
            ];
            return view('',$view);
        }else{
            try{
                M::orderSend(input('post.id'),input('post.send_express_id'),input('post.send_sn'),input('post.send_time'));
                return $this->returnSuccess('发货成功');
            }catch (\Exception $exception){
                global $admin_has_exception;
                $admin_has_exception = true;
                return $this->returnError($exception->getMessage());
            }
        }
    }

    //确认收货
    public function doReceive($id){
        try{
            M::confirmReceive($id);
            return $this->returnSuccess('确认收货成功');
        }catch (\Exception $exception){
            global $admin_has_exception;
            $admin_has_exception = true;
            return $this->returnError($exception->getMessage());
        }
    }

    //发货物流信息
    public function sendInfo(){
        try{
            $id = input('id');
            $info = M::expressInfo($id);

            $view = [
                'info'=>$info,
                'id'=>$id
            ];
            return view('',$view);
        }catch (\Exception $exception){
            return $exception->getMessage();
        }
    }

    //确认核销
    public function doVerify(){
        $id = input('id');
        if(request()->isGet()){
            $order = M::where('id','=',$id)
                ->field('id,order_sn,type,activity_type,verify_type,status')
                ->find();

            $order_goods = Db::name('order_goods')
                ->where('order_id','=',$id)
                ->field('goods_id,title,unit,thumb,sku,spec_item_title,num,leave_num,price,original_price')
                ->select()
                ->toArray();

            $view = [
                'order_goods'=>$order_goods,
                'info'=>$order
            ];
            return view('',$view);
        }else{
            try{
                OrderVerify::verifySub([],input('post.id'),input('post.verify_code'),input('post.num'),3,$this->sesAdminId(),$this->sesAdminUserName());
                return $this->returnSuccess('核销成功');
            }catch (\Exception $exception){
                global $admin_has_exception;
                $admin_has_exception = true;
                return $this->returnError($exception->getMessage());
            }
        }
    }

    //核销记录
    public function verifyInfo()
    {

        if (Request::isAjax()) {

            //分页
            $page = input('page') ? input('page') : 1;
            $pageSize = input('limit') ? input('limit') : config('pageSize');
            $page = ['list_rows' => $pageSize, 'page' => $page];

            //查询条件
            $where = [];

            //条件
            $key = input('key');
            if ($key != '') {
                $where[] = ['id', '=', intval($key)];
            }

            $order_id = input('order_id');
            if ($order_id != '') {
                $where[] = ['order_id', '=',intval($order_id)];
            }

            $type = input('post.type');
            if (!empty($type)) {
                $where[] = ['people_type', '=', intval($type)];
            }

            $merch_worker = input('post.merch_worker');
            if (!empty($merch_worker)) {
                $where[] = ['people_id', '=', intval($merch_worker)];
            }

            $name = input('post.name');
            if ($name!='') {
                $where[] = ['name', 'like', '%'.trim($name).'%'];
            }

            $verify_type = input('post.verify_type');
            if (!empty($verify_type)) {
                $where[] = ['verify_type', '=', intval($verify_type)];
            }

            //条件 开始时间
            $start_time = input('post.start_time');
            if (!empty($start_time)) {
                $where[] = ['create_time', '>=', strtotime($start_time)];
            }

            //条件 结束时间
            $end_time = input('post.end_time');
            if (!empty($end_time)) {
                $where[] = ['create_time', '<=', strtotime($end_time)];
            }

            //排序
            $sort_order = input('sort_order') ? input('sort_order') : 'desc';
            $order = input('sort_order') ? [input('sort_by') => $sort_order] : ['id' => $sort_order];


            $list = OrderVerify::where($where)
                ->order($order)
                ->paginate($page)
                ->each(function ($item){
                    $item['people_type_html'] = get_verify_people_type(2,$item['people_type']);
                    $item['verify_type_html'] = get_goods_verify_type(2,$item['verify_type']);
                    return $item;
                })
                ->toArray();


            return ['code' => 0, 'msg' => '获取成功!', 'data' => $list['data'], 'count' => $list['total'], 'rel' => 1];
        } else {
            $view = [
                'order_id' => input('order_id'),
                'order_sn' => input('order_sn'),
                'people_type'=>get_verify_people_type(),
                'verify_type'=>get_goods_verify_type()
            ];
            return view('', $view);
        }
    }


    //驳回退款
    public function rejectRefund(){
        try {
            OrderRefund::refundCancel(input('post.id'));
            return $this->returnSuccess('驳回退款成功');
        }catch (\Exception $exception){
            global $admin_has_exception;
            $admin_has_exception = true;
            return $this->returnError($exception->getMessage());
        }
    }

    //线下退款
    public function offlineRefund(){
        try {
            OrderRefund::refundOffline(input('post.id'));
            return $this->returnSuccess('线下退款成功');
        }catch (\Exception $exception){
            global $admin_has_exception;
            $admin_has_exception = true;
            return $this->returnError($exception->getMessage());
        }
    }

    //线上退款
    public function onlineRefund(){
        try {
            OrderRefund::refundOnline(input('post.id'),'平台通过退款申请',2);
            return $this->returnSuccess('线上退款成功');
        }catch (\Exception $exception){
            global $admin_has_exception;
            $admin_has_exception = true;
            return $this->returnError($exception->getMessage());
        }
    }

    //驳回换货
    public function rejectChange($id){
        try{
            OrderChange::changeCancel($id);
            return $this->returnSuccess('驳回成功');
        }catch (\Exception $exception){
            global $admin_has_exception;
            $admin_has_exception = true;
            return $this->returnError($exception->getMessage());
        }
    }

    //确认换货
    public function confirmChange(){
        $id = input('id');
        if(request()->isGet()){
            $order = M::where('id','=',$id)
                ->field('id,order_sn,type,activity_type,status,
                send_name,send_mobile,pro_id,city_id,area_id,
                send_address,send_express_id,send_time,send_sn')
                ->find();
            $order['send_address'] = $this->showAddress($order);
            $order['send_time'] = toDate($order['send_time']);
            $view = [
                'express'=>Settings::getSettings(ZFN_SETTINGS_EXPRESS),
                'info'=>$order
            ];
            return view('',$view);
        }else{
            try{
                OrderChange::confirmChange(input('post.id'),input('post.send_express_id'),input('post.send_sn'),input('post.send_time'));
                return $this->returnSuccess('换货成功');
            }catch (\Exception $exception){
                global $admin_has_exception;
                $admin_has_exception = true;
                return $this->returnError($exception->getMessage());
            }
        }
    }

    //批量发货
    public function batch_send(){
        if(request()->isGet()){
            $view = [
                'express'=>Settings::getSettings(ZFN_SETTINGS_EXPRESS),
            ];
            return view('',$view);
        }else{
            try{
                //选择快递公司
                $send_express_id = input('post.send_express_id');
                $excel_path = input('post.excel');

                $data = Excel::readExcel(public_path().$excel_path,0,3);

                unset($data[1]);
                if(count($data)>config('self.batch_send_max')){
                    throw new Exception('每次导入请勿超过'.config('self.batch_send_max').'条');
                }

                $data = array_values($data);

                $result = [
                    'all_num'=>count($data),
                    'success_num'=>0,
                    'success_arr'=>[],
                    'fail_num'=>0,
                    'fail_arr'=>[]
                ];
                $nums = 1;

                foreach ($data as $key=>$item){

                    if(!isset($item['A']) || !isset($item['B']) || !isset($item['C'])){
                        throw new Exception('请下载并使用导入模板');
                    }

                    try {
                        M::orderSend(reInject($item['A']),$send_express_id,reInject($item['B']),reInject($item['C']),'2');
                        //导入成功
                        $result['success_num'] = $result['success_num']+1;
                        $result['success_arr'][] = $item['A'].' 导入成功';
                    }catch (\Exception $e){
                        //导入失败
                        $result['fail_num'] = $result['fail_num']+1;
                        $result['fail_arr'][] = $item['A'].' 导入失败-'.$e->getMessage();
                    }

                    if($nums%100==0){
                        session_write_close();
                        sleep(1);
                    }
                    $nums++;
                }

                return $this->returnSuccess('导入结束',$result);
            }catch (\Exception $exception){
                global $admin_has_exception;
                $admin_has_exception = true;
                return $this->returnError($exception->getMessage());
            }
        }
    }

}